from supermarket import models
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import render, HttpResponse,redirect
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.core import serializers
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
import simplejson

def test(req):
    if req.method == "GET":

        # ContentType表对象有model_class() 方法，取到对应model
        # content = models.ContentType.objects.filter(app_label="supermarket", model="electrics").first()
        # obj = content.model_class() #cloth_class 就相当于models.Electrics
        # rest = obj.objects.all()
        # print(rest)
        #海信电信(id=2)创建一条优惠记录
        # electrics_obj = models.Electrics.objects.filter(name="海信电视").first()
        # print("electrics_obj", electrics_obj)
        # coupon_id = models.Coupon.objects.create(name="电器优惠券", content_obj=electrics_obj)
        #electrics_obj = models.Electrics.objects.filter(name="海信电视").first()
        #models.Coupon.objects.create(name="电器大礼包", content_obj=electrics_obj)
        # 查询优惠券（id=1）绑定了哪个商品
        coupon_obj = models.Coupon.objects.filter(id=1).first()
        electric_obj = coupon_obj.content_obj()
        print(electric_obj)
        b = coupon_obj.content_obj
        print(b)

        # 查询海信电视(id=2)的所有优惠券
        hx_tv = models.Electrics.objects.filter(id=2).first()
        coupon = hx_tv.coupons.all()
        print(coupon)
        for i in coupon:
            print(i.name)
        # 查询obj的所有优惠券：如果没有定义反向查询字段，通过如下方式：
        # content = ContentType.objects.filter(app_label='api', model='model_name').first()
        # res = models.OftenAskedQuestion.objects.filter(content_type=content, object_id=obj.pk).all()

    return HttpResponse("OK")


